import UIKit

class TextField: UIViewController, UITextFieldDelegate {
    
    // MARK: - UITextField文本
    // 基础文本输入框
    private var basicTextField: UITextField!
    
    // 密码输入框
    private var passwordField: UITextField!
    
    // 数字输入框
    private var numberField: UITextField!
    
    // 带清除按钮的输入框
    private var clearableField: UITextField!
    
    // 带图标和自定义样式的输入框
    private var styledField: UITextField!
    
    // 输入结果标签
    private var resultLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground
        setupUI()
    }
    
    private func setupUI() {
        let margin: CGFloat = 20
        let yOffset: CGFloat = 100
        let height: CGFloat = 44
        let width = view.bounds.width - (margin * 2)
        
        // 1. 基础文本输入框
        basicTextField = createTextField(
            frame: CGRect(x: margin, y: yOffset, width: width, height: height),
            placeholder: "普通文本输入",
            keyboardType: .default
        )
        view.addSubview(basicTextField)
        
        // 2. 密码输入框
        passwordField = createTextField(
            frame: CGRect(x: margin, y: yOffset + 60, width: width, height: height),
            placeholder: "密码输入",
            keyboardType: .default
        )
        passwordField.isSecureTextEntry = true
        view.addSubview(passwordField)
        
        // 3. 数字输入框
        numberField = createTextField(
            frame: CGRect(x: margin, y: yOffset + 120, width: width, height: height),
            placeholder: "数字输入",
            keyboardType: .numberPad
        )
        view.addSubview(numberField)
        
        // 4. 带清除按钮的输入框
        clearableField = createTextField(
            frame: CGRect(x: margin, y: yOffset + 180, width: width, height: height),
            placeholder: "带清除按钮",
            keyboardType: .default
        )
        clearableField.clearButtonMode = .whileEditing
        view.addSubview(clearableField)
        
        // 5. 带图标和自定义样式的输入框
        styledField = createTextField(
            frame: CGRect(x: margin, y: yOffset + 240, width: width, height: height),
            placeholder: "带图标和样式",
            keyboardType: .emailAddress
        )
        
        // 添加左侧图标
        let iconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        iconView.image = UIImage(systemName: "envelope")
        iconView.tintColor = .systemGray
        iconView.contentMode = .center
        
        let iconContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 30))
        iconContainerView.addSubview(iconView)
        styledField.leftView = iconContainerView
        styledField.leftViewMode = .always
        
        // 自定义边框样式
        styledField.borderStyle = .none
        styledField.layer.cornerRadius = 8
        styledField.layer.borderWidth = 1
        styledField.layer.borderColor = UIColor.systemGray3.cgColor
        styledField.backgroundColor = .systemBackground
        view.addSubview(styledField)
        
        // 结果标签
        resultLabel = UILabel(frame: CGRect(x: margin, y: yOffset + 320, width: width, height: 80))
        resultLabel.numberOfLines = 0
        resultLabel.textAlignment = .center
        resultLabel.font = UIFont.systemFont(ofSize: 16)
        resultLabel.textColor = .systemBlue
        view.addSubview(resultLabel)
        
        // 提交按钮
        let submitButton = UIButton(type: .system)
        submitButton.frame = CGRect(x: margin, y: yOffset + 420, width: width, height: 50)
        submitButton.setTitle("提交", for: .normal)
        submitButton.backgroundColor = .systemBlue
        submitButton.tintColor = .white
        submitButton.layer.cornerRadius = 8
        submitButton.addTarget(self, action: #selector(submitButtonTapped), for: .touchUpInside)
        view.addSubview(submitButton)
        
        // 添加点击手势收起键盘
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        view.addGestureRecognizer(tapGesture)
    }
    
    private func createTextField(frame: CGRect, placeholder: String, keyboardType: UIKeyboardType) -> UITextField {
        let textField = UITextField(frame: frame)
        //placeholder: String：占位文本（灰色提示文字）。
        textField.placeholder = placeholder
        //keyboardType: UIKeyboardType：键盘类型（如 .default、.numberPad、.emailAddress 等）。
        textField.keyboardType = keyboardType
        //设置键盘右下角 Return 键的样式（显示为 "Done"）。其他可选值包括 .next、.go、.search 等。
        textField.returnKeyType = .done
        //将当前视图控制器设为文本框的代理，以便响应代理方法（如 textFieldShouldReturn）。
        textField.delegate = self
        //关闭自动纠错（输入时不自动修正拼写）。
        textField.autocorrectionType = .no
        //关闭自动大写（输入时不自动将首字母大写）。
        textField.autocapitalizationType = .none
        return textField
    }
    //endEditing(true)：参数 true 表示强制所有控件放弃第一响应者，即使它们不想放弃（例如自定义的输入控件）。
    @objc private func dismissKeyboard() {
        view.endEditing(true)
    }
    
    @objc private func submitButtonTapped() {
        dismissKeyboard()
        //??：空合并操作符，用于在左侧的可选值为 nil 时，提供一个默认值（右侧的表达式）。
        let basicText = basicTextField.text ?? ""
        let password = passwordField.text ?? ""
        let numberText = numberField.text ?? ""
        let clearableText = clearableField.text ?? ""
        let styledText = styledField.text ?? ""
        
        let result = """
            普通文本: \(basicText.isEmpty ? "空" : basicText)
            密码: \(password.isEmpty ? "空" : String(repeating: "*", count: password.count))
            数字: \(numberText.isEmpty ? "空" : numberText)
            带清除按钮: \(clearableText.isEmpty ? "空" : clearableText)
            带图标: \(styledText.isEmpty ? "空" : styledText)
            """
        
        resultLabel.text = result
    }
    
    //  UITextFieldDelegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //当用户点击键盘上的 Return 键时，收起键盘。
        textField.resignFirstResponder()
        return true
    }
}
